package com.wflow.workflow.execute;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wflow.workflow.bean.process.HttpDefinition;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @author : willian fu
 * @date : 2023/10/28
 */
@Slf4j
public class HttpExecute {

    public <T> T execute(HttpDefinition definition, ExecutorService executorService, Class<T> clazz){
        JsExecute jsExecute = new JsExecute(executorService);
        jsExecute.executeVoid("preHandler", definition.getPreHandler(), definition);
        HttpRequest request = HttpUtil.createRequest(definition.getMethod(), definition.getUrl());
        request.timeout(10000);
        definition.getHeaders().forEach(h -> request.header(h.getName(), h.getValue()));
        if ("JSON".equals(definition.getContentType())){
            request.body(JSONObject.toJSONString(definition.getData()), "application/json");
        } else if ("XFORM".equals(definition.getContentType())) {
            definition.getParams().forEach(h -> request.form(h.getName(), h.getValue()));
        }
        HttpResponse response = request.executeAsync();
        Map<String, Object> rsp = new HashMap<>();
        rsp.put("statusCode", response.getStatus());
        rsp.put("headers", response.headers());
        String body = response.body();
        rsp.put("data", JSON.isValid(body) ? JSON.parse(response.body()) : body);
        return jsExecute.execute("aftHandler", definition.getAftHandler(), clazz, rsp);
    }
}
